package com.appbee.media.client.presenter;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Provider;

import com.appbee.core.client.data.BufferedDataProvider;
import com.appbee.core.client.data.Fetch;
import com.appbee.core.client.data.IDataUpdater;
import com.appbee.core.client.data.IFetcher;
import com.appbee.core.client.data.ISortInfo;
import com.appbee.media.shared.MediaProxy;
import com.appbee.media.shared.MediaServiceRequest;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;

public class MediaDataProvider extends AsyncDataProvider<MediaProxy> implements
		IFetcher<MediaProxy>, IDataUpdater<MediaProxy>
{

	private Provider<MediaServiceRequest> mediaServiceProvider;
	private BufferedDataProvider<MediaProxy> buffer = new BufferedDataProvider<MediaProxy>();

	@Inject
	public MediaDataProvider(Provider<MediaServiceRequest> mediaServiceProvider)
	{
		this.mediaServiceProvider = mediaServiceProvider;
		buffer.setFetcher(this);
		buffer.setUpdater(this);
	}

	@Override
	public void fetch(Range range, ISortInfo sortInfo,
			Receiver<List<MediaProxy>> receiver)
	{
		Request<List<MediaProxy>> request = mediaServiceProvider.get().findByRange(range.getStart(), 100);
		request.fire(receiver);
	}

	@Override
	protected void onRangeChanged(HasData<MediaProxy> display)
	{
		buffer.onRangeChange(display);
	}
	
	public void findById(long id,final Receiver<MediaProxy> callback)
	{
		List<Fetch<MediaProxy>> fetchList = buffer.getFetchList();
		for (Fetch<MediaProxy> fetch : fetchList)
		{
			List<MediaProxy> data = fetch.getData();
			for (int i = 0; i < data.size(); i++)
			{
				MediaProxy simplePhotoProxy = data.get(i);
				if (id == simplePhotoProxy.getId())
					callback.onSuccess(simplePhotoProxy);
			}
		}
		Request<MediaProxy> request = mediaServiceProvider.get().findById(id);
		request.fire(callback);
	}
	

}
